package com.yeyaomai.dksns.flowis.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.yeyaomai.dksns.flowis.domain.TrendAnalysisDay;
import com.yeyaomai.dksns.flowis.domain.TrendAnalysisHour;
import com.yeyaomai.dksns.flowis.service.TrendAnalysisDayService;
import com.yeyaomai.dksns.flowis.service.TrendAnalysisHourService;
import com.yeyaomai.dksns.flowis.service.result.DynamicXml;
import com.yeyaomai.dksns.flowis.util.Globals;
import com.yeyaomai.dksns.flowis.util.StringUtil;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

// 模板 zuo
/*
 * @RequestMapping(value = "/{page}", method = RequestMethod.GET) 
 * public  String test(@PathVariable String page, HttpServletRequest request,
 * 
 * HttpServletResponse httpResponse, ModelMap modelMap) 
 * { 
 * 
 * 	Map args = request.getParameterMap();
 * 
 * // 针对请求类似 http://localhost:5555/trend/to-month?a=1 带参数获取方式
 * String a =  request.getParameter("a");
 * 
 * if (page.equals("to-month")) { // 本月统计 return "to-month"; } else if
 * (page.equals("thirdy-day")) { // 最近30天 return "thirdy-day"; } return
 * page;
 * 
 * }
 * 
 */

@Controller
@RequestMapping("/trend/*")
public class TrendAnaysisController {

	@Autowired
	private TrendAnalysisHourService trendAnalysisHourService;
	@Autowired
	private TrendAnalysisDayService trendAnalysisDayService;

	// 本月--zuo
	@RequestMapping(value = "/tomonth")
	public ModelAndView thisMonth(HttpServletRequest request, HttpServletResponse httpResponse, ModelMap modelMap)
			throws ParseException {

		System.out.println(request.getParameter("name"));
		ModelAndView modelAndView = new ModelAndView("to-month");

		String end = Globals.FORMAT_TYPE_A.format(new Date());
		String start = end.replace(end.substring(end.lastIndexOf("-") + 1), "01");

		modelAndView.addObject("date", start);
		modelAndView.addObject("enddate", end);

		List<TrendAnalysisDay> trendAnalysisDayList = new ArrayList<TrendAnalysisDay>();
		List<TrendAnalysisHour> trendAnalysisHourList = new ArrayList<TrendAnalysisHour>();
		// 该时段按天统计表
		// trendAnalysisDayList =
		// trendAnalysisDayService.getTrendAnalysisDayByTrendDay(start.replaceAll("-",
		// ""),
		// end.replaceAll("-", ""));
		trendAnalysisDayList = trendAnalysisDayService.getTrendAnalysisDayByTrendDay(
				Globals.FORMAT_TYPE_A.parse(start), Globals.FORMAT_TYPE_A.parse(end));

		// 该时段按小时统计表
		trendAnalysisHourList = trendAnalysisHourService.getTrendAnalysisHourByHour(Globals.FORMAT_TYPE_A.parse(start),
				Globals.FORMAT_TYPE_A.parse(end));

		handleAllData(modelAndView, trendAnalysisDayList, trendAnalysisHourList);

		return modelAndView;

	}

	// 30天--zuo
	@RequestMapping(value = "/thirtydays")
	public ModelAndView thirtyDays(HttpServletRequest request, HttpServletResponse httpResponse) throws ParseException {
		ModelAndView modelAndView = new ModelAndView("thirty-day");

		String[] retStr = VelocityToolDateUtils.getLatestThirtyDays(new Date(), 30).split(",");

		modelAndView.addObject("date", retStr[0]);
		modelAndView.addObject("enddate", retStr[1]);

		List<TrendAnalysisDay> trendAnalysisDayList = new ArrayList<TrendAnalysisDay>();
		List<TrendAnalysisHour> trendAnalysisHourList = new ArrayList<TrendAnalysisHour>();
		// 该时段按天统计表
		// trendAnalysisDayList = trendAnalysisDayService
		// .getTrendAnalysisDayByTrendDay(retStr[0].replaceAll("-", ""),
		// retStr[1].replaceAll("-", ""));
		trendAnalysisDayList = trendAnalysisDayService.getTrendAnalysisDayByTrendDay(
				Globals.FORMAT_TYPE_A.parse(retStr[0]), Globals.FORMAT_TYPE_A.parse(retStr[1]));
		// 该时段按小时统计表
		trendAnalysisHourList = trendAnalysisHourService.getTrendAnalysisHourByHour(
				Globals.FORMAT_TYPE_A.parse(retStr[0]), Globals.FORMAT_TYPE_A.parse(retStr[1]));
		handleAllData(modelAndView, trendAnalysisDayList, trendAnalysisHourList);

		return modelAndView;

	}

	/**
	 * 今日泫量统计分析
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/today")
	public ModelAndView getTodayCount(HttpServletRequest request) throws ParseException {
		ModelAndView view = new ModelAndView("today-count");
		String time = request.getParameter("time");
		String date = time;
		String todate = Globals.FORMAT_TYPE_A
				.format(Globals.FORMAT_TYPE_A.parse(time).getTime() + 1 * 24 * 3600 * 1000);
		view.addObject("date", time);
		List<TrendAnalysisHour> hour = new ArrayList<TrendAnalysisHour>();

		hour = trendAnalysisHourService.getTrendAnalysisHourByHour(Globals.FORMAT_TYPE_A.parse(date),
				Globals.FORMAT_TYPE_A.parse(todate));

		long pageViewCount = 0;
		long uniqueHost = 0;
		long ip = 0;
		long newUniqueHost = 0;
		Map<String, TrendAnalysisHour> tomap = new HashMap<String, TrendAnalysisHour>(32);
		Map<String, String> map = new TreeMap<String, String>();
		String key = "";
		for (int x = 0; x < 24; x++) {

			if (x < 10) {
				key = "0" + x + ":00";
			} else {
				key = x + ":00";
			}
			map.put(key, "0");
		}
		for (int i = 0; i < hour.size(); i++) {
			TrendAnalysisHour hours = hour.get(i);
			hour.get(i).setAverage(String.format("%.2f", (double) hours.getPageView() / hours.getUniqueHost()));
			tomap.put(hours.getHour(), hours);
			SimpleDateFormat sfmat = new SimpleDateFormat("HH");
			Date dates = sfmat.parse(hour.get(i).getHour());
			hour.get(i).setHour(hour.get(i).getHour() + "-" + sfmat.format(dates.getTime() + 3600 * 1000) + ":00");
			pageViewCount += hours.getPageView();
			uniqueHost += hours.getUniqueHost();
			ip += hours.getIp();
			newUniqueHost += hours.getNewUniqueHost();
		}

		view.addObject("hourList", hour);
		String averageCount = String.format("%.2f", (double) pageViewCount / uniqueHost);
		view.addObject("pageViewCount", pageViewCount);
		view.addObject("uniqueHostCount", uniqueHost);
		view.addObject("ipCount", ip);
		view.addObject("newUniqueHostCount", newUniqueHost);
		view.addObject("averageCount", averageCount);
		StringBuffer pv = new StringBuffer();
		StringBuffer uv = new StringBuffer();
		StringBuffer ipv = new StringBuffer();
		StringBuffer nuv = new StringBuffer();

		Set<String> keys = map.keySet();
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			String value = it.next();
			TrendAnalysisHour tovalue = tomap.get(value);
			if (null == tovalue) {
				pv.append(map.get(value) + ",");
				uv.append(map.get(value) + ",");
				ipv.append(map.get(value) + ",");
				nuv.append(map.get(value) + ",");
			} else {
				pv.append(tomap.get(value).getPageView() + ",");
				uv.append(tomap.get(value).getUniqueHost() + ",");
				ipv.append(tomap.get(value).getIp() + ",");
				nuv.append(tomap.get(value).getNewUniqueHost() + ",");
			}
		}

		pv.append("|PV");
		uv.append("|UV");
		ipv.append("|IP");
		nuv.append("|NUV");
		view.addObject("pv", pv);
		view.addObject("uv", uv);
		view.addObject("ipv", ipv);
		view.addObject("nuv", nuv);
		return view;
	}

	@RequestMapping(value = "/changexml")
	public void changeXml(@RequestParam("value") String value, HttpServletResponse response) throws IOException {
		String xml = DynamicXml.getColumn(value);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	// 看看30天数据
	@RequestMapping(value = "/changeLineXml30")
	public void changeLineXml30(@RequestParam("keyid") String keyid, @RequestParam("startTime") String startTime,
			@RequestParam("endTime") String endTime, HttpServletResponse response) throws ParseException {
		List<TrendAnalysisDay> trendAnalysisDayList = new ArrayList<TrendAnalysisDay>();

		trendAnalysisDayList = trendAnalysisDayService.getTrendAnalysisDayByTrendDay(
				Globals.FORMAT_TYPE_A.parse(startTime), Globals.FORMAT_TYPE_A.parse(endTime));

		// 获取折线图xml
		String xml = DynamicXml.getLine30(trendAnalysisDayList, endTime, keyid);
		response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().print(xml);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 看看本月数据
	@RequestMapping(value = "/changeLineXmlTomonth")
	public void changeLineXmlTomonth(@RequestParam("keyid") String keyid, @RequestParam("startTime") String startTime,
			@RequestParam("endTime") String endTime, HttpServletResponse response) throws ParseException {
		String[] dates = VelocityToolDateUtils.getFirstandLastofcurrentMonth(null).split(",");

		List<TrendAnalysisDay> trendAnalysisDayList = new ArrayList<TrendAnalysisDay>();

		trendAnalysisDayList = trendAnalysisDayService.getTrendAnalysisDayByTrendDay(
				Globals.FORMAT_TYPE_A.parse(startTime), Globals.FORMAT_TYPE_A.parse(endTime));

		// 获取折线图xml
		String xml = DynamicXml.getLinetoMonth(trendAnalysisDayList, dates[0], dates[1], keyid);
		response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().print(xml);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/changelinexml")
	public void changeLineXml(@RequestParam("day") String day, @RequestParam("keyid") String keyid,
			@RequestParam("time") String time, HttpServletResponse response) throws Exception {

		Date date = Globals.FORMAT_TYPE_A.parse(time);
		Date dates = date;
		if (day.equals("yesterday")) {
			dates = new Date(date.getTime() - 1 * 24 * 3600 * 1000);
		}
		if (day.equals("weektoday")) {
			dates = new Date(date.getTime() - 1 * 7 * 24 * 3600 * 1000);
		}
		if (day.equals("monthtoday")) {

			GregorianCalendar da = new GregorianCalendar();
			da.set(Calendar.MONTH, da.get(Calendar.MONTH) - 1);
			dates = da.getTime();
		}

		// 处理今天数据的到时候改成动态，现在没有值。
		String stdate = time;
		String todate = Globals.FORMAT_TYPE_A.format(date.getTime() + 1 * 24 * 3600 * 1000);
		List<TrendAnalysisHour> todayhours = trendAnalysisHourService.getTrendAnalysisHourByHour(
				Globals.FORMAT_TYPE_A.parse(stdate), Globals.FORMAT_TYPE_A.parse(todate));
		// 用于昨天，上周同期，本月同期的查询的日期参数
		String todaydatest = Globals.FORMAT_TYPE_A.format(dates);
		String todaydateto = Globals.FORMAT_TYPE_A.format(new Date(dates.getTime() + 1 * 24 * 3600 * 1000));
		List<TrendAnalysisHour> beforehours = trendAnalysisHourService.getTrendAnalysisHourByHour(
				Globals.FORMAT_TYPE_A.parse(todaydatest), Globals.FORMAT_TYPE_A.parse(todaydateto));
		String xml = DynamicXml.getLine(beforehours, todayhours, keyid, stdate, todaydatest);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	/**
	 * 昨日统计
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/yesterday")
	public ModelAndView getYesterdayCount(HttpServletRequest request) throws ParseException {
		String time = request.getParameter("time");
		ModelAndView view = new ModelAndView("yesterday-count");
		String date = time;
		String todate = Globals.FORMAT_TYPE_A
				.format(Globals.FORMAT_TYPE_A.parse(time).getTime() + 1 * 24 * 3600 * 1000);
		view.addObject("date", time);
		List<TrendAnalysisHour> hour = new ArrayList<TrendAnalysisHour>();

		hour = trendAnalysisHourService.getTrendAnalysisHourByHour(Globals.FORMAT_TYPE_A.parse(date),
				Globals.FORMAT_TYPE_A.parse(todate));

		long pageViewCount = 0;
		long uniqueHost = 0;
		long ip = 0;
		long newUniqueHost = 0;
		Map<String, TrendAnalysisHour> tomap = new HashMap<String, TrendAnalysisHour>(32);
		Map<String, String> map = new TreeMap<String, String>();
		String key = "";
		for (int x = 0; x < 24; x++) {

			if (x < 10) {
				key = "0" + x + ":00";
			} else {
				key = x + ":00";
			}
			map.put(key, "0");
		}
		for (int i = 0; i < hour.size(); i++) {
			TrendAnalysisHour hours = hour.get(i);
			hour.get(i).setAverage(String.format("%.2f", (double) hours.getPageView() / hours.getUniqueHost()));
			tomap.put(hours.getHour(), hours);
			SimpleDateFormat sfmat = new SimpleDateFormat("HH");
			Date mat = sfmat.parse(hour.get(i).getHour());
			hour.get(i).setHour(hour.get(i).getHour() + "-" + sfmat.format(mat.getTime() + 3600 * 1000) + ":00");
			pageViewCount += hours.getPageView();
			uniqueHost += hours.getUniqueHost();
			ip += hours.getIp();
			newUniqueHost += hours.getNewUniqueHost();
		}
		view.addObject("hourList", hour);
		String averageCount = String.format("%.2f", (double) pageViewCount / uniqueHost);
		view.addObject("pageViewCount", pageViewCount);
		view.addObject("uniqueHostCount", uniqueHost);
		view.addObject("ipCount", ip);
		view.addObject("newUniqueHostCount", newUniqueHost);
		view.addObject("averageCount", averageCount);
		StringBuffer pv = new StringBuffer();
		StringBuffer uv = new StringBuffer();
		StringBuffer ipv = new StringBuffer();
		StringBuffer nuv = new StringBuffer();
		Set<String> keys = map.keySet();
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			String value = it.next();
			TrendAnalysisHour tovalue = tomap.get(value);
			if (null == tovalue) {
				pv.append(map.get(value) + ",");
				uv.append(map.get(value) + ",");
				ipv.append(map.get(value) + ",");
				nuv.append(map.get(value) + ",");
			} else {
				pv.append(tomap.get(value).getPageView() + ",");
				uv.append(tomap.get(value).getUniqueHost() + ",");
				ipv.append(tomap.get(value).getIp() + ",");
				nuv.append(tomap.get(value).getNewUniqueHost() + ",");
			}
		}

		pv.append("|PV");
		uv.append("|UV");
		ipv.append("|IP");
		nuv.append("|NUV");
		view.addObject("pv", pv);
		view.addObject("uv", uv);
		view.addObject("ipv", ipv);
		view.addObject("nuv", nuv);
		view.addObject("stringUtil", StringUtil.class);
		return view;
	}

	// 处理业务数据
	private void handleAllData(ModelAndView modelAndView, List<TrendAnalysisDay> trendAnalysisDayList,
			List<TrendAnalysisHour> trendAnalysisHourList) {
		long pageViewCount = 0;
		long uniqueHost = 0;
		long ip = 0;
		long newUniqueHost = 0;

		for (TrendAnalysisDay day : trendAnalysisDayList) {
			day.setAverage(String.format("%.2f", (double) day.getPageView() / day.getUniqueHost()));
			pageViewCount += day.getPageView();
			uniqueHost += day.getUniqueHost();
			ip += day.getIp();
			newUniqueHost += day.getNewUniqueHost();
		}

		String averageCount = String.format("%.2f", (double) pageViewCount / uniqueHost);
		// 统计各个时刻的量

		Map<String, Integer> pvMap = new TreeMap<String, Integer>();
		Map<String, Integer> ipMap = new TreeMap<String, Integer>();
		Map<String, Integer> uvMap = new TreeMap<String, Integer>();
		Map<String, Integer> nuvMap = new TreeMap<String, Integer>();
		Map<String, TrendAnalysisHour> objectMap = new TreeMap<String, TrendAnalysisHour>();
		// 填充map
		for (int i = 0; i < trendAnalysisHourList.size(); i++) {
			TrendAnalysisHour hour = trendAnalysisHourList.get(i);

			handleMap(pvMap, hour.getHour(), hour.getPageView());
			handleMap(ipMap, hour.getHour(), hour.getIp());
			handleMap(uvMap, hour.getHour(), hour.getUniqueHost());
			handleMap(nuvMap, hour.getHour(), hour.getNewUniqueHost());

		}
		// 设值
		generateOjbectMap(pvMap, ipMap, uvMap, nuvMap, objectMap);
		modelAndView.addObject("averageCount", averageCount);
		modelAndView.addObject("pageViewCount", pageViewCount);
		modelAndView.addObject("uniqueHostCount", uniqueHost);
		modelAndView.addObject("ipCount", ip);
		modelAndView.addObject("newUniqueHostCount", newUniqueHost);
		modelAndView.addObject("trendAnalysisDayList", trendAnalysisDayList);
		modelAndView.addObject("trendAnalysisHourList", trendAnalysisHourList);
		modelAndView.addObject("objectMap", objectMap);

		String pv = handleString(pvMap, "PV");
		String uv = handleString(ipMap, "UV");
		String ipv = handleString(uvMap, "IP");
		String nuv = handleString(nuvMap, "NUV");

		modelAndView.addObject("pv", pv);
		modelAndView.addObject("uv", uv);
		modelAndView.addObject("ipv", ipv);
		modelAndView.addObject("nuv", nuv);
	}

	// 组装单时段对象map
	private void generateOjbectMap(Map<String, Integer> pvMap, Map<String, Integer> ipMap, Map<String, Integer> uvMap,
			Map<String, Integer> nuvMap, Map<String, TrendAnalysisHour> objectMap) {
		for (Entry<String, Integer> entry : pvMap.entrySet()) {
			String key = entry.getKey();
			TrendAnalysisHour h = new TrendAnalysisHour();
			h.setPageView(entry.getValue());
			h.setIp(ipMap.get(key));
			h.setUniqueHost(uvMap.get(key));
			h.setNewUniqueHost(nuvMap.get(key));
			objectMap.put(key, h);
		}
	}

	// 渲染map
	private void handleMap(Map<String, Integer> handledMap, String key, Integer value) {
		// long pv = hour.getPageView();
		if (handledMap.containsKey(key)) {
			Integer newpv = value + handledMap.get(key);
			// 覆盖
			handledMap.put(key, newpv);
		} else {
			handledMap.put(key, value);
		}

	}

	// 拼装String...
	private String handleString(Map<String, Integer> handledMap, String key) {
		StringBuffer sb = new StringBuffer();
		// initial Stringbuffer...
		for (int i = 0; i < 24; i++) {
			if (i < 23) {
				if (i < 10) {
					sb.append("0" + i + ":00,");
				} else {
					sb.append(i + ":00,");
				}
			} else {
				sb.append(i + ":00|" + key);
			}
		}
		String retStr = sb.toString();
		for (Entry<String, Integer> entry : handledMap.entrySet()) {
			if (retStr.indexOf(entry.getKey()) != -1) {
				retStr = retStr.replace(entry.getKey(), entry.getValue().toString());
			}
		}
		retStr = retStr.replaceAll("[0-9]{2}:[0-9]{2}", "0");
		return retStr;
	}
}
